<template>
  <div class="c2c-publish">
    <div class="page-header">
      <h2 class="page-title">发布C2C订单</h2>
      <p class="page-subtitle">发布买单或卖单，与其他用户交易</p>
    </div>
    
    <el-card class="publish-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Plus /></el-icon>
          <span>发布订单</span>
          <div style="flex: 1"></div>
          <div class="exchange-rate-info" v-if="exchangeRate > 0">
            <span class="rate-label">当前汇率：</span>
            <span class="rate-value">1 USDT = ¥{{ formatAmount(exchangeRate) }}</span>
            <el-button 
              text 
              size="small" 
              @click="refreshRate"
              :loading="rateLoading"
              style="margin-left: 8px"
            >
              <el-icon><Refresh /></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="publishFormRef"
        :model="publishForm"
        :rules="publishRules"
        label-width="120px"
      >
        <el-form-item label="订单类型" prop="type">
          <el-radio-group v-model="publishForm.type">
            <el-radio label="buy">买单（我要买币）</el-radio>
            <el-radio label="sell">卖单（我要卖币）</el-radio>
          </el-radio-group>
          <div class="form-tip">
            {{ publishForm.type === 'buy' ? '买单：您用人民币购买USDT' : '卖单：您出售USDT获得人民币' }}
          </div>
        </el-form-item>
        
        <el-form-item label="金额单位" prop="amountUnit">
          <el-radio-group v-model="publishForm.amountUnit">
            <el-radio label="CNY">人民币（¥）</el-radio>
            <el-radio label="USDT">USDT（U）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          :label="publishForm.amountUnit === 'CNY' ? '交易金额（人民币）' : '交易金额（USDT）'" 
          prop="amount"
        >
          <el-input-number
            v-model="publishForm.amount"
            :min="0.01"
            :precision="publishForm.amountUnit === 'CNY' ? 2 : 4"
            :step="publishForm.amountUnit === 'CNY' ? 0.01 : 0.0001"
            style="width: 100%"
            placeholder="请输入交易金额"
          />
          <div class="form-tip">
            <template v-if="publishForm.amountUnit === 'CNY'">
              <span v-if="publishForm.amount > 0">
                约等于 {{ formatAmount(convertedAmount.usdt) }} USDT
                <span v-if="publishForm.type === 'sell'">
                  （可用余额: {{ formatBalance(balance) }} USDT）
                </span>
              </span>
              <span v-else>请输入交易金额</span>
            </template>
            <template v-else>
              <span v-if="publishForm.amount > 0">
                约等于 ¥{{ formatAmount(convertedAmount.cny) }}
                <span v-if="publishForm.type === 'sell'">
                  （可用余额: {{ formatBalance(balance) }} USDT）
                </span>
              </span>
              <span v-else>请输入交易金额</span>
            </template>
          </div>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="publishForm.paymentMethod" style="width: 100%" placeholder="请选择支付方式">
            <el-option label="支付宝" value="支付宝" />
            <el-option label="微信" value="微信" />
            <el-option label="银行卡" value="银行卡" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注（可选）" prop="remark">
          <el-input
            v-model="publishForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息，如：交易时间、联系方式等"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handlePublish"
          >
            发布订单
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.push('/c2c')">返回列表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { c2cApi } from '../api/c2c'
import { walletApi } from '../api/wallet'
import { getUSDTToCNYRate, usdtToCny, cnyToUsdt } from '../utils/exchangeRate'

const publishFormRef = ref<FormInstance>()
const loading = ref(false)
const rateLoading = ref(false)
const balance = ref(0)
const exchangeRate = ref(0)

const publishForm = reactive({
  type: 'buy' as 'buy' | 'sell',
  amountUnit: 'CNY' as 'CNY' | 'USDT',
  amount: 0,
  paymentMethod: '',
  remark: ''
})

const publishRules = {
  type: [
    { required: true, message: '请选择订单类型', trigger: 'change' }
  ],
  amountUnit: [
    { required: true, message: '请选择金额单位', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入交易金额', trigger: 'blur' },
    { 
      validator: (rule: any, value: number, callback: Function) => {
        if (value <= 0) {
          callback(new Error('金额必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 计算转换后的金额
const convertedAmount = computed(() => {
  if (!publishForm.amount || !exchangeRate.value) {
    return { usdt: 0, cny: 0 }
  }
  
  if (publishForm.amountUnit === 'CNY') {
    return {
      usdt: cnyToUsdt(publishForm.amount, exchangeRate.value),
      cny: publishForm.amount
    }
  } else {
    return {
      usdt: publishForm.amount,
      cny: usdtToCny(publishForm.amount, exchangeRate.value)
    }
  }
})

onMounted(async () => {
  await Promise.all([loadBalance(), loadExchangeRate()])
})

// 监听订单类型变化，如果是卖单需要检查余额
watch(() => publishForm.type, async (newType) => {
  if (newType === 'sell') {
    await loadBalance()
  }
})

const loadBalance = async () => {
  try {
    const balanceData = await walletApi.getBalance()
    balance.value = balanceData.total || 0
  } catch (error) {
    console.error('加载余额失败:', error)
  }
}

const loadExchangeRate = async () => {
  rateLoading.value = true
  try {
    const rate = await getUSDTToCNYRate()
    exchangeRate.value = rate
  } catch (error) {
    console.error('加载汇率失败:', error)
    ElMessage.warning('获取汇率失败，使用默认汇率')
    exchangeRate.value = 7.2
  } finally {
    rateLoading.value = false
  }
}

const refreshRate = async () => {
  await loadExchangeRate()
  ElMessage.success('汇率已更新')
}

const handlePublish = async () => {
  if (!publishFormRef.value) return
  
  await publishFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 计算实际的USDT数量和单价
    const usdtAmount = convertedAmount.value.usdt
    const cnyAmount = convertedAmount.value.cny
    const price = exchangeRate.value // 使用当前汇率作为单价
    
    // 验证金额
    if (usdtAmount <= 0) {
      ElMessage.error('交易金额无效')
      return
    }
    
    // 如果是卖单，检查余额
    if (publishForm.type === 'sell' && usdtAmount > balance.value) {
      ElMessage.error(`余额不足，可用余额: ${formatBalance(balance.value)} USDT`)
      return
    }
    
    // 设置最小和最大金额（允许部分交易，最小10%）
    const minAmount = usdtAmount * 0.1
    const maxAmount = usdtAmount
    
    try {
      const orderType = publishForm.type === 'buy' ? '买单' : '卖单'
      const amountText = publishForm.amountUnit === 'CNY' 
        ? `¥${formatAmount(cnyAmount)} (约 ${formatAmount(usdtAmount)} USDT)`
        : `${formatAmount(usdtAmount)} USDT (约 ¥${formatAmount(cnyAmount)})`
      
      await ElMessageBox.confirm(
        `确认发布${orderType}？\n金额: ${amountText}\n单价: ¥${formatAmount(price)}/USDT`,
        '确认发布订单',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      loading.value = true
      await c2cApi.createOrder({
        type: publishForm.type,
        currency: 'USDT',
        amount: usdtAmount,
        price: price,
        minAmount: minAmount,
        maxAmount: maxAmount,
        paymentMethod: publishForm.paymentMethod,
        remark: publishForm.remark
      })
      
      ElMessage.success('订单发布成功！')
      resetForm()
      // 跳转到我的订单页面
      setTimeout(() => {
        window.location.href = '/c2c/my-orders'
      }, 1500)
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '发布订单失败')
      }
    } finally {
      loading.value = false
    }
  })
}

const resetForm = () => {
  if (publishFormRef.value) {
    publishFormRef.value.resetFields()
  }
  publishForm.type = 'buy'
  publishForm.amountUnit = 'CNY'
  publishForm.amount = 0
  publishForm.paymentMethod = ''
  publishForm.remark = ''
}

const formatBalance = (value: number) => {
  return value.toFixed(4)
}

const formatAmount = (value: number) => {
  if (value >= 1000) {
    return value.toFixed(2)
  } else if (value >= 1) {
    return value.toFixed(2)
  } else {
    return value.toFixed(4)
  }
}
</script>

<style scoped>
.c2c-publish {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.publish-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.exchange-rate-info {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.rate-label {
  color: #909399;
  margin-right: 4px;
}

.rate-value {
  color: #409eff;
  font-weight: 500;
}
</style>

